package com.bridgetree.jubaocrm.ui;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.Toast;

import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.Volley;
import com.bridgetree.jubaocrm.R;
import com.bridgetree.jubaocrm.model.CRMUserBaseInfo;
import com.bridgetree.jubaocrm.service.JsonObjectPostRequest;
import com.bridgetree.jubaocrm.service.Network;
import com.bridgetree.jubaocrm.util.LoginError;
import com.bridgetree.jubaocrm.util.LoginInterface;
import com.bridgetree.jubaocrm.util.Projects;

public class LoginActivity extends Activity {
	private Context mContext;
	private static String TAG = "LoginActivity";
	private SharedPreferences prefs;
	private EditText userNameTx;
	private EditText passwordTx;
	private InputMethodManager manager;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.login);
		mContext=this;

		manager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
		prefs = PreferenceManager.getDefaultSharedPreferences(LoginActivity.this);

		DisplayMetrics dm = new DisplayMetrics();
		// 获取屏幕信息
		getWindowManager().getDefaultDisplay().getMetrics(dm);
		int screenWidth = dm.widthPixels;
		int screenHeight = dm.heightPixels;
		float screenScale = dm.scaledDensity;
		Contents.AdapterSetting(screenWidth, screenHeight, screenScale);

		userNameTx = (EditText) findViewById(R.id.login_username);
		passwordTx = (EditText) findViewById(R.id.login_password);
		String userName = prefs.getString(Contents.KEY_PERSONAL_USERNAME, "");
		String password = prefs.getString(Contents.KEY_PERSONAL_PASSWORD, "");
//				userNameTx.setText("183954573@qq.com");
//				passwordTx.setText("323391");
		if(!userName.equals("")){
			userNameTx.setText(userName);
		}
		if(!password.equals("")){
			passwordTx.setText(password);
		}
		Log.i(TAG, "LoginActivity.....");

		findViewById(R.id.login_submit_btn).setOnClickListener(
				new OnClickListener() {
					@Override
					public void onClick(View v) {
						String userNameTxString = userNameTx.getText().toString();
						String passwordTxString = passwordTx.getText().toString();
						getJSONByVolley(userNameTxString,passwordTxString);
						// startActivity(new Intent(LoginActivity.this,
						// ViewPageActivity.class));
					}
				});
		
		String userNames = userNameTx.getText().toString();
		String passwords =  passwordTx.getText().toString();
//		if(!userNames.equals("") && !passwords.equals("")){
//			getJSONByVolley(userNames,passwords);
//		}
	}

	private void openDailog(String title, String content) {
		new AlertDialog.Builder(mContext).setTitle(title)
		.setMessage(content).setPositiveButton("确定", null).show();
	}

	@Override
	public boolean onTouchEvent(MotionEvent event) {
		// TODO Auto-generated method stub
		if (event.getAction() == MotionEvent.ACTION_DOWN) {
			if (getCurrentFocus() != null
					&& getCurrentFocus().getWindowToken() != null) {
				manager.hideSoftInputFromWindow(getCurrentFocus()
						.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
			}
		}
		return super.onTouchEvent(event);
	}

	/**
	 * 登录
	 */
	private void getJSONByVolley(final String userNameTxString,final String passwordTxString) {

		Network mNetword = new Network(mContext);
		if (!mNetword.isNetworkConnected()) {
			openDailog("网络提示", "网络未连接,请连接网络！");
		} else if (userNameTxString.equals("") || passwordTxString.equals("")) {
			openDailog("输入提示", "账号或密码不能为空！");
		} else {
			HashMap<String, String> mMap = new HashMap<String, String>();
			mMap.put("username", userNameTxString);
			mMap.put("password", passwordTxString);
			mMap.put("validation", CRMUserBaseInfo.kValication);
			String URL = Network.API_DOMAIN+ "/login";

			final ProgressDialog progressDialog = ProgressDialog.show(this, "请稍等", "...Loading...");
			RequestQueue requestQueue = Volley.newRequestQueue(mContext);
			JsonObjectPostRequest jsonObjectPostRequest = new JsonObjectPostRequest(
					URL, new Response.Listener<JSONObject>() {

						@Override
						public void onResponse(JSONObject response) {
							try {
								if (progressDialog.isShowing()&&progressDialog!=null) {  
									progressDialog.dismiss();  
								}
								String user_id="";
								String token="";
								Log.e("wop"," response = "+response.toString());
								LoginInterface mLoginInterface =new LoginInterface();
								if (!response.isNull("user_id")) {
									user_id = response.get("user_id").toString();
									mLoginInterface.setUser_id(user_id);
								}
								if (!response.isNull("token")) {
									token = response.get("token").toString();
									mLoginInterface.setToken(token);
								}
								if (!response.isNull("my_projects")) {
									org.json.JSONArray jsonArr;
									List<Projects> my_projects = new ArrayList<Projects>();
									jsonArr = response.getJSONArray("my_projects");
									if (jsonArr.length() > 0) {
										for (int i = 0; i < jsonArr.length(); i++) {
											Projects my_project = new Projects();
											JSONObject jsonObj2 = jsonArr.getJSONObject(i);
											if (!jsonObj2.isNull("is_approved")) {
												boolean is_approved = Boolean.valueOf(jsonObj2.getString("is_approved"));
												my_project.setIs_approved(is_approved);
											}
											if (!jsonObj2.isNull("client_id")) {
												String client_id = jsonObj2.getString("client_id");
												my_project.setClient_id(client_id);
											}
											if (!jsonObj2.isNull("project_name")) {
												String project_name = jsonObj2.getString("project_name");
												my_project.setProject_name(project_name);
											}
											if (!jsonObj2.isNull("project_id")) {
												String project_id = jsonObj2.getString("project_id");
												my_project.setProject_id(project_id);
											}
											my_project.setUser_id(user_id);
											my_project.setToken(token);
											my_projects.add(my_project);
										}
									}
									mLoginInterface.setMy_projects(my_projects);
								}
								if (!response.isNull("fullname")) {
									String fullname = response.get("fullname").toString();
									mLoginInterface.setFullname(fullname);
								}
								if (!response.isNull("errors")) {
									String errors = response.get("errors").toString();
									if (errors.equals("[]")) {
										prefs.edit().putString(Contents.KEY_PERSONAL_USERNAME, userNameTxString).commit();
										prefs.edit().putString(Contents.KEY_PERSONAL_PASSWORD, passwordTxString).commit();
										prefs.edit().putString(Contents.KEY_PERSONAL_LOGIN_USEID, mLoginInterface.getUser_id()).commit();
										prefs.edit().putString(Contents.KEY_PERSONAL_LOGIN_TAKEN,  mLoginInterface.getToken()).commit();
										prefs.edit().putBoolean(Contents.KEY_PERSONAL_LOGIN_STATE, true).commit();
										Intent intent = new Intent(mContext,ViewPageActivity.class);
										Bundle bundle = new Bundle();
										bundle.putSerializable("my_projects", (Serializable) mLoginInterface.getMy_projects());
										bundle.putSerializable("LoginInterface", (Serializable) mLoginInterface);
										intent.putExtras(bundle);
										startActivity(intent);
										finish();
									} else {
										org.json.JSONArray jsonArr;
										if (!response.isNull("errors")) {
											LoginError mLoginError = new LoginError();
											jsonArr = response.getJSONArray("errors");
											if (jsonArr.length() > 0) {
												for (int i = 0; i < jsonArr.length(); i++) {
													JSONObject jsonObj2 = jsonArr.getJSONObject(i);
													if (!jsonObj2.isNull("desc")) {
														String desc = jsonObj2.getString("desc");
														passwordTx.setText("");
														openDailog("登录失败提示", desc);
														mLoginError.setDesc(desc);
													}
													if (!jsonObj2.isNull("value")) {
														String value = jsonObj2.getString("value");
														mLoginError.setValue(value);
													}
												}
											}
											mLoginInterface.setErrors(mLoginError);
										}
									}
								}
							} catch (JSONException e) {
								e.printStackTrace();
							}
						}
					}, new Response.ErrorListener() {

						@Override
						public void onErrorResponse(VolleyError error) {
							Toast.makeText(LoginActivity.this, "网络未连接！",
									Toast.LENGTH_LONG).show();
						}
					}, mMap);
			requestQueue.add(jsonObjectPostRequest);
		}

	}

	// 1. 替换加号图片
	// 2. 网络没开提示/登录错误提示
	// 3. 下拉刷新加 上次更新时间
	// 4. 首页菜单下面的蓝色横条左边有点长

}
